<template>
  <div class="user">
    <img class="avatar" :src="dalImg(user.avatar)" alt="图片丢了" />
    <h4>{{ user.nickName ? user.nickName : user.userName }}</h4>
    <p>积分:{{ user.score }}</p>
    <Button
      type="primary"
      style="display: block; margin: 8px auto; border-radius: 10px"
      @click="checkIn"
      >签到</Button
    >
    <cell title="我的订单" is-link :to="{ name: 'MyOrder' }" />
    <cell title="个人信息" is-link value="" :to="{ name: 'userInfo' }" />
    <cell title="修改密码" is-link value="" :to="{ name: 'changePwd' }" />
    <Button
      type="danger"
      size="large"
      style="width: 75vw; display: block; margin: 8px auto"
      @click="loginOut"
      >退出</Button
    >
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Cell, Button, Toast } from "vant";
import { removeToken } from "../utils/auth";
import { userInfoAPI, checkInAPI } from "../server/auth";
import { dalImg, isCheckedToday } from "../utils/tools";
import { useCart } from "../store/carts-num";

const store = useCart();
const { resetCart } = store;
const user = ref("");
const { push } = useRouter();
// 退出登录
const loginOut = () => {
  removeToken();
  resetCart();
  push({
    name: "home",
  });
};
// 获取用户信息
const loadUserInfo = () => {
  userInfoAPI().then((res) => {
    // console.log(res, "用户信息");
    user.value = res.data;
  });
};
// 页面初始化先获取用户信息
loadUserInfo();
// 签到
const checkIn = () => {
  isCheckedToday().then(async (res) => {
    // console.log(res);
    if (!res) {
      await checkInAPI();
      loadUserInfo();
    } else {
      Toast("今日已签到");
    }
  });
};
</script>

<style lang="scss">
.user {
  /* padding: 8px; */
  .avatar {
    display: block;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    margin: 24px auto;
  }
  h4 {
    text-align: center;
  }
  p {
    text-align: center;
  }
}
</style>
